package com.sinodata.bsm.center.web.action.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.cache.DimensionCache;
import com.sinodata.bsm.center.cache.DimensionTypeCache;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.config.DimensionService;
import com.sinodata.bsm.center.service.config.DimensionTypeService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.utils.StringUtil;
import com.sinodata.bsm.common.vo.Dimension;
import com.sinodata.bsm.common.vo.DimensionType;
import com.sinodata.bsm.common.vo.ProtocolParameter;

public class DimensionTypeConfigAction extends BaseAction<DimensionType> {
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -2423730569613866497L;

    @Autowired
    private DimensionTypeService dimensionTypeService;
    @Autowired
    private DimensionTypeCache dimensionTypeCache;
    @Autowired
    private DimensionService dimensionService;
    @Autowired
    private DimensionCache dimensionCache;

    private Long[] ids;
    private Long id;
    private DimensionType dimensionType;

    public String common() {
        return "common";
    }

    /**
     * 添加跳转页面
     * 
     * @return
     */
    public String add() {
        return "add";
    }

    public String validateDimensionTypeName() {
        try {
            if ("true".equals(request.getParameter("isValideFlag"))) {
                Condition condition = new Condition();
                Map<String, String> map = new HashMap<String, String>();
                map.put("dimensionTypeName", request.getParameter("dimensionTypeName"));
                condition.setWhere(map);
                int count = dimensionTypeService.getTotal(condition);
                if (count == 0) {
                    renderText("true");
                } else {
                    renderText("false");
                }
            } else {
                renderText("true");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String delete() throws Exception {
        // TODO Auto-generated method stub
        // 缓存判断是否删除
        for (Long id : ids) {
            if (dimensionTypeCache.get(id) == null) {
                renderText("false");
                return null;
            }
        }
        // 删除维度类型下的维度
        dimensionService.deleteDimensionByTypeid(ids);

        // 删除维度类型
        dimensionTypeService.delete(ids);

        for (Long id : ids) {
            dimensionTypeCache.remove(id);
            // 将维度类型下对应的维度删除
            List<Dimension> dimensionList = dimensionCache.getDimensionByType(id);
            for (Dimension dimension : dimensionList) {
                dimensionCache.remove(dimension.getId());
            }

        }
        renderText("true");
        return null;
    }

    @Override
    public String input() throws Exception {
        // TODO Auto-generated method stub
        DimensionType dimensionType = dimensionTypeCache.get(Long.valueOf(request.getParameter("id")));
        List<Dimension> dimensionByList = dimensionCache.getDimensionByType(dimensionType.getId());
        for (Dimension dimension : dimensionByList) {
            Long dimensionParentId = dimension.getParentId();
            if (dimensionParentId != null) {
                Dimension dimensionParent = dimensionCache.get(dimensionParentId);
                if (dimensionParent != null && dimensionParent.getParentId() != null) {
                    Struts2Utils.getRequest().setAttribute("isRelation", "1");
                }
            }
        }
        Struts2Utils.getRequest().setAttribute("dimensionType", dimensionType);
        return "update";
    }

    @Override
    public String list() throws Exception {
        try {
            // TODO Auto-generated method stub
            String dimensionTypeName = request.getParameter("dimensionTypeName");
            Condition condition = new Condition();
            Map<String, String> map = new HashMap<String, String>();
            if (!StringUtil.isEmpty(dimensionTypeName)) {
                map.put("dimensionTypeName", dimensionTypeName);
            }
            // 分页排序
            Map<String, String> orderMap = new HashMap<String, String>();
            String order = request.getParameter("sSortDir_0");
            String col = request.getParameter("mDataProp_" + request.getParameter("iSortCol_0"));
            if (!col.equals("checkbox") && !col.equals("op")) {
                orderMap.put(col, order);
            }
            condition.setWhere(map);
            // 分页参数
            Page<DimensionType> page = new Page<DimensionType>();
            page.setPageNo(Integer.valueOf(request.getParameter("iDisplayStart")) / Integer.valueOf(request.getParameter("iDisplayLength")) + 1);
            page.setPageSize(Integer.valueOf(request.getParameter("iDisplayLength")));
            // 分页数据
            Page<DimensionType> dimensionTypePage = dimensionTypeService.findByPage(page, condition);
            // Json数据的封装
            JSONObject json = new JSONObject();
            json.element("iTotalRecords", page.getTotal());
            json.element("iTotalDisplayRecords", page.getTotal());
            JSONArray array = new JSONArray();
            boolean sysManager = UserFunctionValidate.sysFunctionValidate(FunctionConstants.SYSTEM_MANAGER);
            for (DimensionType dimensionType : dimensionTypePage.getRows()) {
                JSONObject obj = new JSONObject();
                obj.element("checkbox", "<div align='center'><input type='checkbox' name='dt_check' id='dt_check' value='" + dimensionType.getId() + "'></div>");
                if (sysManager) {
                    obj.element("op", "<div style='width: 80px'>&nbsp;&nbsp;<a href='javascript:edit(" + dimensionType.getId() + ");'><img src='../style/default/bsm/images/edit.gif' title='修改'></a>&nbsp;<a href='javascript:deleteOne(" + dimensionType.getId() + ");'><img src='../style/default/bsm/images/delete.gif' title='删除'></a>&nbsp;<a href='javascript:dimensionByTypeId(" + dimensionType.getId() + ");'><img src='../style/default/bsm/images/view.gif' title='维度管理'></a><div>");
                } else {
                    obj.element("op", "<div style='width: 80px'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:test(" + dimensionType.getId() + ");'><img src='../style/default/bsm/images/test.gif' title='修改'></a><div>");
                }
                obj.element("id", dimensionType.getId());
                obj.element("dimensionTypeName", dimensionType.getDimensionTypeName());
                obj.element("isRelation", dimensionType.getIsRelation().longValue() == 0 ? "一层" : "多层");
                array.add(obj);
            }
            json.element("aaData", array);
            renderText(json.toString());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {
        // TODO Auto-generated method stub
        if (id != null) {
            dimensionType = dimensionTypeCache.get(id);
            if (dimensionType == null) {
                dimensionType = new DimensionType();
            }
        } else {
            dimensionType = new DimensionType();
        }

    }

    @Override
    public String save() throws Exception {
        // TODO Auto-generated method stub
        // 修改
        if (dimensionType.getId() != null) {
            if (dimensionTypeCache.get(dimensionType.getId()) != null) {
                dimensionTypeService.update(dimensionType);
                dimensionTypeCache.put(dimensionType.getId(), dimensionType);
            }
        } else {
            dimensionTypeService.add(dimensionType);
            dimensionTypeCache.put(dimensionType.getId(), dimensionType);
        }
        renderText("true");
        return null;
    }

    public String checkDeleted() {
        JSONObject ob = new JSONObject();
        if (dimensionTypeCache.get(id) == null) {
            ob.element("flag", false);
        } else {
            ob.element("flag", true);
        }
        Struts2Utils.renderJson(ob.toString());
        return null;
    }

    @Override
    public DimensionType getModel() {
        // TODO Auto-generated method stub
        return this.dimensionType;
    }

    public Long[] getIds() {
        return ids;
    }

    public void setIds(Long[] ids) {
        this.ids = ids;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}
